﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using KeaoBase;
using System.Xml;
using System.Threading;
using KeaoMDS.Auth;
using KeaoUpLoad;

namespace KeaoMDS
{
    public partial class Login : Form
    {
        public Login()
        {
            InitializeComponent();
        }

        private bool m_Auth = false;

        private void Login_Load(object sender, EventArgs e)
        {

            try
            {
                if (!KeaoUtils._DB.InitDataBase(KeaoUtils.Decrypt(KeaoUtils.ConfigGetNodeAttr("系统配置", "数据库"))))
                {
                    KeaoUtils.ShowWarnMessage("数据库连接失败！");
                    Environment.Exit(0);
                }
                else
                {
                    //ThreadPool.QueueUserWorkItem(new WaitCallback(Auth));
                    Thread t = new Thread(new ThreadStart(Auth));
                    t.Start();
                    XmlNodeList nodeList = KeaoUtils.ConfigGetNodeListByTag("用户列表");
                    foreach (XmlNode node in nodeList[0].ChildNodes)
                    {
                        txt_userName.Items.Add(node.InnerText);
                    }
                }
            }
            catch (Exception err)
            {
                KeaoUtils.LogTxt(string.Format("{0}_加载登录界面异常。", err.Message));
            }

        }

        private void button2_Click(object sender, EventArgs e)
        {
            Environment.Exit(0);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string p = System.Diagnostics.Process.GetCurrentProcess().ProcessName;
            System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName(p);
            if (processes.Length > 1)
            {
                MessageBox.Show("主程序正在运行中，操作无法完成，不允许打开多个主程序。", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Environment.Exit(0);
                return;
            }

            if (m_Auth)
            {
                #region 验证注册信息
                string authTimeOut = KeaoUtils.ConfigGetNodeAttr("注册信息", "注册码");
                if (string.IsNullOrEmpty(authTimeOut))
                {
                    KeaoUtils.ShowWarnMessage("注册信息错误，请输入注册码。");
                    RuanJianShouQuan ruanJian = new RuanJianShouQuan(false);
                    if (ruanJian.ShowDialog() == DialogResult.Yes)
                    {
                        string zhuCeMa = KeaoUtils.Decrypt(ruanJian.m_ZhuCeMa);
                        if (string.IsNullOrEmpty(zhuCeMa) || !zhuCeMa.StartsWith("Keao"))
                        {
                            KeaoUtils.ShowWarnMessage("注册信息错误。");
                            Environment.Exit(0);
                            return;
                        }
                        else
                        {
                            authTimeOut = zhuCeMa.Replace("Keao", "");
                            DateTime d = DateTime.Parse(authTimeOut);
                            if (d < DateTime.Today)
                            {
                                KeaoUtils.ShowWarnMessage("注册信息错误。");
                                Environment.Exit(0);
                                return;
                            }
                            else
                            {
                                KeaoUtils.ConfigSetNodeAttr("注册信息", "注册码", KeaoUtils.Encrypt(zhuCeMa));
                            }
                        }
                    }
                    else
                    {
                        return;
                    }
                }
                else
                {
                    string currentZhuCeMa = KeaoUtils.Decrypt(authTimeOut);
                    if (currentZhuCeMa.StartsWith("Keao"))
                    {
                        currentZhuCeMa = currentZhuCeMa.Replace("Keao", "");
                        DateTime currentdate = DateTime.Parse(currentZhuCeMa);
                        if (currentdate < DateTime.Today)
                        {
                            KeaoUtils.ShowWarnMessage("注册信息错误，请输入注册码。");
                            RuanJianShouQuan ruanJian = new RuanJianShouQuan(false);
                            if (ruanJian.ShowDialog() == DialogResult.Yes)
                            {
                                string zhuCeMa = KeaoUtils.Decrypt(ruanJian.m_ZhuCeMa);
                                if (string.IsNullOrEmpty(zhuCeMa) || !zhuCeMa.StartsWith("Keao"))
                                {
                                    KeaoUtils.ShowWarnMessage("注册信息错误。");
                                    Environment.Exit(0);
                                    return;
                                }
                                else
                                {
                                    authTimeOut = zhuCeMa.Replace("Keao", "");
                                    DateTime d = DateTime.Parse(authTimeOut);
                                    if (d < DateTime.Today)
                                    {
                                        KeaoUtils.ShowWarnMessage("注册信息错误。");
                                        Environment.Exit(0);
                                        return;
                                    }
                                    else
                                    {
                                        KeaoUtils.ConfigSetNodeAttr("注册信息", "注册码", KeaoUtils.Encrypt(zhuCeMa));
                                    }
                                }
                            }
                            else
                            {
                                return;
                            }
                        }
                    }
                }
#endregion

                if (string.IsNullOrEmpty(txt_userName.Text) || string.IsNullOrEmpty(txt_pwd.Text))
                {
                    KeaoUtils.ShowInfoMessage("请输入用户名和密码。");
                    return;
                }
                string CreateAndCondition = KeaoUtils._DB.CreateAndCondition("yonghudengluming", DataValueCommonType.字符串, txt_userName.Text, "", SearchConditionType.等于);
                CreateAndCondition += KeaoUtils._DB.CreateAndCondition("yonghumima", DataValueCommonType.字符串, KeaoUtils.Encrypt(txt_pwd.Text), "", SearchConditionType.等于);
                Dictionary<string,string> leftTables = new Dictionary<string,string>();
                leftTables.Add("tbl_juese","juesemingcheng=yonghujuese");
                DataTable Dt = KeaoUtils._DB.GetDataTableByCondition("tbl_yonghu","tbl_yonghu.id,yonghuxingming,yonghumima,juesequanxian",leftTables, CreateAndCondition,null,null);
                if (Dt == null)
                {
                    return;
                }
                if (Dt.Rows.Count > 0)
                {
                    if (string.Format("{0}", Dt.Rows[0]["juesequanxian"]).Contains("登录系统"))
                    {
                        KeaoUtils._CurrentUserRow = Dt.Rows[0];
                        DialogResult = DialogResult.OK;
                        //ThreadPool.QueueUserWorkItem(new WaitCallback( YongHu2Config), txt_userName.Text);
                        Thread t = new Thread(new ParameterizedThreadStart(YongHu2Config));
                        t.Start(txt_userName.Text);
                    }
                    else 
                    {
                        KeaoUtils.ShowInfoMessage("该用户没有权限登录系统。");
                        return;
                    }
                }
                else
                {
                    KeaoUtils.ShowInfoMessage("用户名或密码错误，请重新输入。");
                    return;
                }
            }
            else
            {
                try
                {
                    RuanJianShouQuan authSoftware = new RuanJianShouQuan(true);
                    if (authSoftware.ShowDialog() == DialogResult.Yes)
                    {
                        Application.Restart();
                    }
                    else
                    {
                        KeaoUtils.ShowWarnMessage("软件未经授权，暂时无法使用。");
                        Environment.Exit(0);
                    }
                }
                catch (Exception err)
                {
                    KeaoUtils.LogTxt(string.Format("注册异常。{0}", err.Message));
                }
            }

        }

        private void Auth()
        {
            #region 验证是否经过授权
            DataTable Dt = KeaoUtils._DB.GetDataTableByCondition("tbl_zhuce");
            if (Dt == null)
            {
                return;
            }
            if (Dt.Rows.Count==0)
            {
                TableRow newRow = new TableRow("tbl_zhuce", KeaoUtils.GetGUID(), DBCtl.插入);
                newRow.DataCols.Add(new TableCol() { ValueType = DataValueCommonType.字符串, ColName = "cpuid", ValueMember = KeaoUtils.getCpuID() });
                if (KeaoUtils._DB.SaveTableRows(newRow) <= 0)
                {
                    m_Auth = false;
                }
                else
                {
                    m_Auth = true;
                }
            }
            else
            {
                if (!Dt.Rows[0]["cpuid"].Equals(KeaoUtils.getCpuID()))
                {
                    m_Auth = false;
                }
                else
                {
                    m_Auth = true;
                }
            }
            #endregion
        }

        private void txt_pwd_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                button1_Click(sender, e);
            }
        }


        private void YongHu2Config(object Args)
        {
            try
            {
                XmlNodeList nodeList = KeaoUtils.ConfigGetNodeListByTag("用户");
                foreach (XmlNode node in nodeList)
                {
                    if (Args.Equals(node.InnerText))
                    {
                        return;
                    }
                }
                KeaoUtils.ConfigAddChildNodesInnerText("用户列表", "用户", string.Format("{0}", Args));
            }
            catch (Exception err)
            {
                KeaoUtils.LogTxt(string.Format("写用户到配置文件异常。{0}", err.Message));
            }
        }
 
     

    }
}
